<template>
  <div class="chatroom-container">
    <el-row>
      <el-col :span="24">
        <select v-model="selectedIcon" @change="onIconChange" class="icon-dropdown">
          <option value disabled selected>选择图标</option>
          <option v-for="icon in icons" :key="icon" :value="icon">{{ icon }}</option>
        </select>
        <p class="chatroom-title">
          <span class="material-icons chatroom-icon">{{ selectedIcon }}</span>
          员工聊天室
          <span class="material-icons chatroom-icon">{{ selectedIcon }}</span>
        </p>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="18" :offset="3" class="messages-container" id="textarea">
        <!-- 消息在这里显示 -->
      </el-col>
      <el-col :span="3">
        <img src="../assets/hmbb1.gif" class="side-img" />
      </el-col>
    </el-row>
    <el-row v-if="!joined">
      <el-col :span="12" :offset="6">
        <div class="input-group">
          <el-input placeholder="请输入用户名" v-model="userName" class="input-with-button"></el-input>
          <el-button type="primary" @click="join">加入聊天室</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="18" :offset="3">
        <el-dropdown @command="addEmoji">
          <span class="el-dropdown-link">
            😊
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <div v-for="(emojiGroup, index) in groupedEmojis" :key="index" class="emoji-row">
              <el-dropdown-item
                v-for="emoji in emojiGroup"
                :key="emoji"
                :command="emoji"
              >{{ emoji }}</el-dropdown-item>
            </div>
          </el-dropdown-menu>
        </el-dropdown>
        <el-input type="text" placeholder="说点什么..." v-model="message" class="message-input"></el-input>
        <el-button type="primary" @click="send">发送</el-button>
      </el-col>
    </el-row>
  </div>
</template>
  
  <script>
export default {
  data() {
    return {
      onIconChange: "",
      groupedEmojis: [],
      selectedIcon: "",
      icons: [
        "pets", // 猫咪
        "mood", // 笑脸
        "message", // 消息
        "android", // Android 徽标
        "assignment", // 作业
        "bluetooth", // 蓝牙
        "book", // 书籍
        "bookmark", // 书签
        "camera_alt", // 相机
        "chat_bubble_outline", // 聊天
        "dashboard", // 仪表盘
        "brightness_high" // 高亮度
      ],
      url: "ws://192.168.2.202/WebSocketHandler/",
      ws: null,
      userName: "",
      message: "",
      joined: false, // 添加这个新属性来控制加入状态,
      emojis: [
        "😀",
        "😂",
        "🤣",
        "😍",
        "😘",
        "😜",
        "👍",
        "👏",
        "💪",
        "🙌",
        "😎",
        "😊",
        "😁",
        "😚",
        "😳",
        "😌",
        "😃",
        "😆",
        "😋",
        "😉",
        "😄",
        "😇",
        "🙂",
        "🙃",
        "😺",
        "😸",
        "😹",
        "😻",
        "😼",
        "😽",
        "😾",
        "😿",
        "🙀"
      ]
    };
  },
  methods: {
    addEmoji(emoji) {
      this.message += emoji; // 将选定的表情加到信息里
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$el.querySelector(".messages-container");
        container.scrollTop = container.scrollHeight;
      });
    },
    join() {
      if (this.userName == "") {
        alert("请输入您的大名！");
        return;
      }

      // 如果已有连接，先关闭
      if (this.ws) {
        this.ws.close();
      }

      this.ws = new WebSocket(this.url + this.userName);

      const userName = this.userName;
      let _this = this;
      // 监听WebSocket连接打开事件
      this.ws.onopen = function() {
        console.log(userName + "连接成功！");
        _this.joined = true; // 标记为已加入
        _this.scrollToBottom();
      };

      // 监听消息
      this.ws.onmessage = function(result) {
        const textarea = document.getElementById("textarea");
        if (textarea) {
          // 检查 textarea 是否存在
          let beforeHtml = textarea.innerHTML;
          let msg = result.data.split(":");
          if (_this.userName == msg[0]) {
            textarea.innerHTML =
              beforeHtml +
              "<span style=' background-color: #409EFF;  float:right; '>" +
              msg[1] +
              ":" +
              msg[0] +
              "</span>" +
              "</br>";
          } else {
            textarea.innerHTML =
              beforeHtml + "<span>" + result.data + "</span>" + "</br>";
          }
        } else {
          console.error("Message container not found.");
          // 可以在这里处理错误，比如显示提示信息或者忽略该消息
        }
      };

      this.ws.onclose = function() {
        const textarea = document.getElementById("textarea");
        if (_this.joined) {
          console.log(this.userName);
          textarea.append("用户：" + userName + "离开聊天室 \n");
          _this.joined = false;
        }
      };
    },
    send() {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(this.message);
        this.message = "";
      } else {
        alert("请先加入聊天室。");
      }
    },
    beforeDestroy() {
      // 组件销毁之前，确保WebSocket连接被关闭
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
      next();
    }
  },
  created() {
    let i,
      j,
      chunk = 5;
    for (i = 0, j = this.emojis.length; i < j; i += chunk) {
      this.groupedEmojis.push(this.emojis.slice(i, i + chunk));
    }
  }
};
</script>
  
  <style scoped >
.emoji-row {
  display: flex;
  justify-content: space-around;
}

.el-dropdown-item {
  flex: 0 0 20%; /* 每行显示五个 */
}

.chatroom-container {
  padding: 20px;
  background-color: #1e1e1e; /* 暗色背景 */
  color: #c0c0c0; /* 浅色文字 */
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(255, 255, 255, 0.1); /* 浅色阴影 */
}

.chatroom-title {
  font-size: 24px;
  color: #4caf50; /* 明亮绿色标题 */
  text-align: center;
  margin-bottom: 20px;
}

/* 将消息容器的高度调高，例如从 400px 调整为 500px */
.messages-container {
  background-color: #7a7a84; /* 暗色消息背景 */
  height: 550px; /* 增加高度 */
  overflow-y: auto;
  padding: 15px;
  border-radius: 5px;
  box-shadow: inset 0 0 10px #0e0e0e; /* 更深的阴影描边 */
  color: #d3d3d3; /* 浅色文字，用于消息文本 */
}

/* 调整输入框的宽度，使其更短 */
.input-group .el-input,
.message-input {
  width: calc(100% - 150px); /* 减少输入框宽度 */
}

.message {
  padding: 10px 15px;
  border-radius: 20px;
  display: inline-block;
  max-width: 70%;
  margin: 5px 0;
  position: relative;
  animation: slideIn 0.5s ease-out;
  color: #000; /* 深色文字，增强对比 */
}

.message.sender {
  background-color: #409eff;
  color: #fff;
  float: right;
  clear: both;
}

.message.receiver {
  background-color: #f0f0f0;
  color: #333;
  float: left;
  clear: both;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-input {
  width: calc(100% - 150px); /* 调整后的宽度 */
  color: #fff; /* 白色文字 */
  background-color: #555; /* 暗色背景 */
  border-color: #333; /* 更暗的边框颜色 */
}

.el-dropdown-link {
  color: #4caf50; /* 明亮绿色，同标题 */
  cursor: pointer;
}

.el-dropdown-menu {
  background-color: #555; /* 暗色背景 */
}

.el-dropdown-item {
  color: #d3d3d3; /* 浅色文字 */
}

.el-button {
  background-color: #409eff; /* 按钮背景 */
  border-color: #409eff; /* 按钮边框 */
  color: #fff; /* 按钮文字颜色 */
}

.el-button:hover {
  background-color: #66b3ff; /* 按钮悬停颜色 */
  border-color: #66b3ff; /* 按钮悬停边框颜色 */
}

.input-group {
  margin-top: 20px; /* 在输入组和上方内容之间增加间隔 */
}

.el-input-group__prepend,
.el-input-group__append {
  background-color: #333; /* 为输入框前后添加的部分设置背景色 */
}

.input-with-button .el-input__inner {
  border-radius: 0; /* 统一圆角风格 */
  border-right: 0; /* 移除输入框右边框，贴合按钮 */
}

.el-button {
  border-left: 0; /* 移除按钮左边框，贴合输入框 */
}

.el-button {
  text-align: center; /* 文字居中  */
  border: none;
  color: white; /* 文字颜色白色  */
  cursor: pointer;
  display: inline-block;
  background: linear-gradient(
    to right,
    rgb(176, 119, 218),
    rgb(129, 214, 238)
  ); /* 渐变效果更换为浅紫色到浅蓝色 */
  transition-property: background-color, transform; /* 添加过渡属性 */
  transition-duration: 0.3s; /* 过渡持续时间 */
}

.icon-dropdown {
  display: block;
  width: 100%;
  max-width: 300px;
  padding: 10px;
  margin-bottom: 20px;
  font-family: "Material Icons";
  font-size: 20px;
  cursor: pointer;
}

.selected-icon {
  font-family: "Material Icons";
  display: inline-flex;
  font-feature-settings: "liga";
  font-size: 48px; /* or desired size */
}

.side-img {
  width: 80%; /* 根据需要减小宽度 */
  height: auto; /* 自动适应高度 */
  margin-top: 100px; /* 上移图片 */
  margin-left: 20px; /* 右移图片 */
}
</style>